const { chromium } = require('playwright');
const ExcelJS = require('exceljs');
const os = require('os');
const path = require('path');
const ProgressBar = require('progress'); // 引入进度条库

(async () => {
  const browser = await chromium.launch({
    headless: false,
    channel: 'msedge',
    args: ['--start-maximized'],
    executablePath: 'C:\\Program Files (x86)\\Microsoft\\Edge\\Application\\msedge.exe'
  });
  const page = await browser.newPage();
  const workbook = new ExcelJS.Workbook();
  const worksheet = workbook.addWorksheet('EPD Data');

  await page.goto('https://www.eco-platform.org/epd-data.html', {
    waitUntil: 'domcontentloaded',
    timeout: 120000
  });
  await page.click('button.cc-btn.warn[data-deny-all]');
  await page.click('button.buttonlink.btl-check');
  
  await page.waitForSelector('.p-datatable-table.ng-star-inserted');
  await page.waitForTimeout(5000);

  // 获取表头信息
  const headers = await page.$$eval('.p-datatable-table.ng-star-inserted thead th', headers => 
    headers.map(header => header.innerText.trim())
  );

  // 设置 Excel 列头
  worksheet.columns = headers.map((header, index) => ({
    header,
    key: `col${index}`,
    width: 20
  }));

  const results = [];
  const maxPages = 2293; // 设置最大翻页次数

  // 初始化进度条
  const bar = new ProgressBar('  抓取进度 [:bar] :percent :etas', {
    complete: '=',
    incomplete: ' ',
    width: 20,
    total: maxPages
  });

  for (let pageNum = 1; pageNum <= maxPages; pageNum++) {
    console.log(`正在抓取第 ${pageNum}/${maxPages} 页...`);
    
    const pageData = await page.$$eval('.p-datatable-table.ng-star-inserted tbody tr', rows => 
      rows.map(row => {
        const cells = row.querySelectorAll('td');
        return Array.from(cells).map(cell => cell.innerText.trim());
      })
    );
    
    results.push(...pageData);
    // 将当前页数据添加到 Excel 工作表
    pageData.forEach(row => {
      const rowData = {};
      headers.forEach((_, index) => {
        rowData[`col${index}`] = row[index];
      });
      worksheet.addRow(rowData);
    });

    try {
      await page.waitForTimeout(2000);
      const nextButton = await page.$('.p-ripple.p-element.p-paginator-next.p-paginator-element.p-link');
      
      if (!nextButton) break;
      
      const referenceText = await page.$eval('.p-datatable-table.ng-star-inserted tbody tr:first-child td:nth-child(2)', 
        cell => cell.innerText.trim()
      );

      await nextButton.click();
      await page.waitForFunction((refText) => {
        const firstCell = document.querySelector('.p-datatable-table.ng-star-inserted tbody tr:first-child td:nth-child(2)');
        return firstCell && firstCell.innerText.trim() !== refText;
      }, {}, referenceText);

    } catch (error) {
      console.log('翻页失败:', error);
      break;
    }
    // 更新进度条
    bar.tick();
  }

  // 保存Excel文件
  const desktopPath = path.join(os.homedir(), 'Desktop');
  const filePath = path.join(desktopPath, 'EPD_Data.xlsx');
  await workbook.xlsx.writeFile(filePath);
  console.log(`数据已保存到 ${filePath}，共 ${results.length} 条记录`);
  await browser.close();
})();
